package com.heima.behavior.filter;

import com.heima.model.common.whitelist.WhiteList;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author XHui
 * @Since 2024/2/22 11:32
 * @Version 1.0
 */
@Slf4j
@WebFilter(filterName = "behaviorTokenFilter", urlPatterns = "/*")
@Order(1)
@Component
public class BehaviorTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        // 1. token已经被网关层解析过了，直接从 header 中获取token中的payload
        // 1.1 getHeader是HttpServletRequest的方法，
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        /*boolean isPass = WhiteList.isPass(request.getRequestURI());

        if (!isPass) {

        }*/
        String userId = request.getHeader("userId");

        // 1.2 若userIdInt=0，代表用户没有通过账号密码登录。而是设备登录, 设备登录不存入用户信息
        if(StringUtils.isNotBlank(userId) && Integer.valueOf(userId) != 0){
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            AppThreadLocalUtils.setUser(apUser);
        }
        // 2. 继续前往下一个过滤器，若果是最后一个过滤器，则直接进入到controller层
        filterChain.doFilter(servletRequest, servletResponse);
        // 3. 请求得到响应之后，同样经过过滤器
        // 3.1 清除线程变量中的用户信息  防止当前线程被线程池复用，导致该用户信息被其他用户使用
        AppThreadLocalUtils.clear();
    }
}
